package flc.ast.activity;

import androidx.activity.result.ActivityResult;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.SeekBar;

import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.ImageUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.blankj.utilcode.util.UriUtils;
import com.stark.cartoonutil.lib.BaseController;
import com.stark.cartoonutil.lib.CartoonsController;
import com.stark.cartoonutil.lib.utils.ImgUtil;

import java.io.File;

import flc.ast.BaseAc;
import flc.ast.HomeActivity;
import flc.ast.R;
import flc.ast.databinding.ActivityResultBinding;
import io.reactivex.rxjava3.core.ObservableEmitter;
import jp.co.cyberagent.android.gpuimage.filter.GPUImageToonFilter;
import stark.common.basic.utils.FastClickUtil;
import stark.common.basic.utils.FileP2pUtil;
import stark.common.basic.utils.FileUtil;
import stark.common.basic.utils.IntentUtil;
import stark.common.basic.utils.RxUtil;
import stark.common.basic.utils.UriUtil;

public class ResultActivity extends BaseAc<ActivityResultBinding> {

    public static boolean isCamera = false;
    public static Bitmap resultImg;//拍照结果
    public static String resultPath;//图片详情
    private int style=1;
    private CartoonsController cartoonsController;
    private Bitmap bitmap;
    private int defWidth = -1;
    private int defHeight = -1;
    private String mTmpShareFilePath;
    private String savePath="";




    @Override
    protected int onCreate() {
        return R.layout.activity_result;
    }

    @Override
    protected void initView() {
        mDataBinding.ivResultBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        mDataBinding.llStyle1.setOnClickListener(this);
        mDataBinding.llStyle2.setOnClickListener(this);
        mDataBinding.ivShare.setOnClickListener(this);
        mDataBinding.ivSave.setOnClickListener(this);
        mDataBinding.seekbarLevel.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                GPUImageToonFilter filter = (GPUImageToonFilter) mDataBinding.gpuImgView.getFilter();
                filter.setLineSize(calLineSize(progress));
                mDataBinding.gpuImgView.requestRender();
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
            }
        });
    }

    @Override
    protected void onClickCallback(View v) {
        if (FastClickUtil.isFastClick()) return;
        switch (v.getId()){
            case R.id.llStyle1://手绘风格
                if (style==1) return;
                showDialog(getString(R.string.loading));
                clearSelection();
                mDataBinding.glImgView.setVisibility(View.VISIBLE);
                mDataBinding.gpuImgView.setVisibility(View.GONE);
                mDataBinding.tvStyle1.setTextColor(Color.parseColor("#FFFFFFFF"));
                mDataBinding.llStyle1.setBackgroundResource(R.drawable.axuanzhong);
                mDataBinding.llAdjust.setVisibility(View.INVISIBLE);
                style=1;
                mDataBinding.glImgView.setImageSrc(bitmap.copy(bitmap.getConfig(), bitmap.isMutable()), true);
                cartoonsController.applyCartoonsModel(new BaseController.IApplyModelCallback() {
                    @Override
                    public void onComplete() {
                        dismissDialog();
                        ToastUtils.showShort(R.string.convert_suc);
                    }
                });
                break;
            case R.id.llStyle2://美式风格
                if (style==2) return;
                clearSelection();
                mDataBinding.glImgView.setVisibility(View.GONE);
                mDataBinding.gpuImgView.setVisibility(View.VISIBLE);
                mDataBinding.tvStyle2.setTextColor(Color.parseColor("#FFFFFFFF"));
                mDataBinding.llStyle2.setBackgroundResource(R.drawable.axuanzhong);
                mDataBinding.llAdjust.setVisibility(View.VISIBLE);
                style=2;
                break;
            case R.id.ivShare://分享
                if (TextUtils.isEmpty(savePath)){
                    ToastUtils.showShort(getString(R.string.please_save));
                    return;
                }
                IntentUtil.shareImage(mContext,"",savePath);
                break;
            case R.id.ivSave://保存
                if (style==1){
                    saveImg1();
                }else if (style==2){
                    saveImg2();
                }
                break;
        }
    }

    @Override
    protected void initData() {
//        mDataBinding.gpuImgView.setImage(Uri.parse(resultUri));
        mDataBinding.gpuImgView.setFilter(new GPUImageToonFilter());
        //该控制器用于对图片进行动漫化处理
        mDataBinding.glImgView.setVisibility(View.VISIBLE);
        mDataBinding.gpuImgView.setVisibility(View.GONE);
        cartoonsController = new CartoonsController(mContext, mDataBinding.glImgView);
        showDialog(getString(R.string.loading));
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                if (defWidth < 0) {
                    defWidth = mDataBinding.glImgView.getWidth();
                    defHeight = mDataBinding.glImgView.getHeight();
                }
                if (isCamera){
                    bitmap=resultImg;
                }else {
                    bitmap = ImgUtil.Companion.getCompressedBitmapByFilePath(resultPath, defWidth, defHeight);
                }
                ViewGroup.LayoutParams layoutParams = mDataBinding.glImgView.getLayoutParams();
                layoutParams.width = bitmap.getWidth();
                layoutParams.height = bitmap.getHeight();
                mDataBinding.gpuImgView.setImage(bitmap);
                mDataBinding.glImgView.setLayoutParams(layoutParams);
                mDataBinding.glImgView.setImageSrc(bitmap.copy(bitmap.getConfig(), bitmap.isMutable()), true);
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        cartoonsController.applyCartoonsModel(new BaseController.IApplyModelCallback() {
                            @Override
                            public void onComplete() {
                                dismissDialog();
                            }
                        });
                    }
                }, 500);
            }
        }, 500);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (!TextUtils.isEmpty(mTmpShareFilePath)) {
            FileUtils.delete(mTmpShareFilePath);
            mTmpShareFilePath = null;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //这里要释放资源
        if (cartoonsController != null) {
            cartoonsController.release();
            cartoonsController = null;
        }
    }

    private float calLineSize(int progress) {
        float start = 0f;
        float end = 5.0f;
        float ret = (end - start) * progress / 100f + start;
        return ret;
    }

    private void saveImg1() {
        showDialog(getString(R.string.save_ing));
        float aspectRatio = mDataBinding.glImgView.getWidth() * 1f / mDataBinding.glImgView.getHeight();
        cartoonsController.save(aspectRatio, new BaseController.ISaveCallback() {
            @Override
            public void onResult(@Nullable Uri fileUri) {
                dismissDialog();
                if (fileUri != null) {
//                    startActivity(HomeActivity.class);
                    File file =UriUtils.uri2File(fileUri);
                    savePath=file.getPath();
                }
                ToastUtils.showShort(fileUri != null ? getString(R.string.save_to_album) : getString(R.string.save_failure));
            }
        });
    }

    private void saveImg2() {
        showDialog(getString(R.string.save_ing));
        RxUtil.create(new RxUtil.Callback<Uri>() {
            @Override
            public void doBackground(ObservableEmitter<Uri> emitter) {
                Uri uri = null;
                try {
                    Bitmap bitmap = mDataBinding.gpuImgView.capture();
                    uri = FileP2pUtil.saveBitmap2Jpg(mContext, bitmap);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                emitter.onNext(uri);
            }

            @Override
            public void accept(Uri uri) {
                dismissDialog();
                if (uri != null) {
//                    startActivity(HomeActivity.class);
                    File file =UriUtils.uri2File(uri);
                    savePath=file.getPath();
                }
                ToastUtils.showShort(uri != null ? getString(R.string.save_to_album) : getString(R.string.save_failure));
            }
        });
    }

    private void clearSelection(){
        mDataBinding.llStyle1.setBackgroundResource(0);
        mDataBinding.llStyle2.setBackgroundResource(0);
        mDataBinding.tvStyle1.setTextColor(Color.parseColor("#FF000000"));
        mDataBinding.tvStyle2.setTextColor(Color.parseColor("#FF000000"));
    }

}